<template>
  <div class="cont" v-show="contShow">
    <!-- 搜索工作栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="cont_top" label-width="50px">
      <el-form-item style="margin-right: 12px">
        <el-button link type="primary" @click="addbtn" class="btnhover" style="
            width: 90px;
            height: 30px;
            background-color: rgba(218, 111, 40, 1);
            color: rgba(255, 255, 255, 1);
          ">新增居民</el-button>
        <el-button link type="primary" @click="downloadbtn" class="btnhover" style="
            width: 90px;
            height: 30px;
            background-color: rgba(218, 111, 40, 1);
            color: rgba(255, 255, 255, 1);
          ">下载模版</el-button>
        <ResidentImportForm ref="importFormRef" @success="getList" />
        <el-button link type="primary" @click="importbtn" class="btnhover" style="
            width: 90px;
            height: 30px;
            margin-left: 12px;
            background-color: rgba(218, 111, 40, 1);
            color: rgba(255, 255, 255, 1);
          ">批量导入</el-button>
        <el-button link type="primary" @click="exportbtn" class="btnhover" style="
            width: 90px;
            height: 30px;
            background-color: rgba(218, 111, 40, 1);
            color: rgba(255, 255, 255, 1);
          ">批量导出</el-button>
        <el-button link type="primary" @click="alldelbtn" class="btnhover" style="
            width: 90px;
            height: 30px;
            background-color: rgba(218, 111, 40, 1);
            color: rgba(255, 255, 255, 1);
          ">批量删除</el-button>
      </el-form-item>
      <el-form-item label="姓名" prop="residentName" style="margin-right: 17px">
        <el-input v-model="queryParams.residentName" placeholder="" @keyup.enter="handleQuery" style="width: 170px" />
      </el-form-item>
      <el-form-item label="房屋" prop="houseNumber" style="margin-right: 17px">
        <el-input v-model="queryParams.houseNumber" placeholder="" @keyup.enter="handleQuery" style="width: 170px" />
      </el-form-item>
      <el-form-item label="类型" prop="residentType" style="margin-right: 17px">
        <el-select v-model="queryParams.residentType" @change="handleQuery" placeholder="" placement="bottom"
          style="width: 140px">
          <el-option v-for="item in optiontype" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus" style="margin-right: 17px" label-width="74px">
        <el-select v-model="queryParams.auditStatus" @change="handleQuery" placeholder="" placement="bottom"
          style="width: 140px">
          <el-option v-for="item in optionstate" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item style="margin-right: 0">
        <el-button @click="handleQuery" class="btn btnsearch">查询</el-button>
        <el-button @click="resetQuery" class="btn btnreset">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 列表 -->
    <el-table v-loading="loading" element-loading-text="Loading..." :data="list"
      style="margin-bottom: 20px;min-height: 435px;" :header-cell-style="{ background: '#F0F0F0' }"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" />
      <el-table-column align="center" label="姓名" show-overflow-tooltip min-width="120">
        <template #default="scope">
          <div class="namecont">
            {{ scope.row.residentName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="性别" prop="sex" min-width="120">
        <template #default="{ row }">
          {{ sexTypeObj[row.sex] }}
        </template>
      </el-table-column>
      <el-table-column :formatter="dateFormatter2" align="center" label="出生日期" prop="birthDate" min-width="150" />
      <el-table-column align="center" label="民族" prop="nation" min-width="120">
        <template #default="{ row }">
          {{ nationtypeRelate(row.nation) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="类型" prop="residentType" min-width="150">
        <template #default="{ row }">
          {{ typetypeRelate(row.residentType) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="房屋" show-overflow-tooltip prop="houseNumber" min-width="160">
        <template #default="{ row }">
          <div class="namecont">
            {{ row.houseNumber === "" ? '--' : row.houseNumber }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否户主" prop="isHolder" min-width="120">
        <template #default="{ row }">
          {{ isHolderTypeObj[row.isHolder] }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="与户主关系" prop="relationship" min-width="150">
        <template #default="{ row }">
          {{ holdtypeRelate(row.relationship) === "" ? '--' : holdtypeRelate(row.relationship) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="户主" show-overflow-tooltip prop="holderId" min-width="150">
        <template #default="{ row }">
          <div class="namecont">
            {{ holdIdtypeRelate(row.holderId) === "" ? '--' : holdIdtypeRelate(row.holderId) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="户籍地" show-overflow-tooltip prop="address" min-width="220">
        <template #default="{ row }">
          <div class="namecont">
            {{ row.address === "" ? '--' : row.address }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="居民标签" prop="residentLabel" width="300" show-overflow-tooltip>
        <template #default="scope">
          <div v-if="scope.row.residentLabel.join() !== ''"
            :style="scope.row.residentLabel.length >= 3 ? 'display: flex;justify-content:left;' : 'display: flex;justify-content:center'">
            <div class="label_style">
              <div v-for="(item, index) in scope.row.residentLabel" class="identity_style" :key="index">
                {{ labeltypeRelate(item) }}
              </div>
            </div>
          </div>
          <div v-else style="display: flex;justify-content:center;">
            --
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="审核状态" prop="auditStatus" min-width="120">
        <template #default="scope">
          <div :style="stateText(scope.row.auditStatus)" class="state_style">{{
            stateTypeObj[scope.row.auditStatus] }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" width="200">
        <template #default="scope">
          <el-button link type="primary" class="btnhover" @click="detailsbtn(scope.row)"
            style="color: #3c88f0">详情</el-button>
          <el-button link type="primary" class="btnhover" @click="editbtn(scope.row)"
            style="color: #3c88f0">编辑</el-button>
          <el-button link type="primary" class="btnhover" @click="delbtn(scope.row)"
            style="color: #3c88f0">删除</el-button>
          <el-button v-if="scope.row.auditStatus === 1" v-hasPermi="['dv_affairs:resident_record:shenhe']" link
            type="primary" class="btnhover" @click="statebtn(scope.row)" style="color: #3c88f0">审核</el-button>
          <div v-else style="width: 42px" v-hasPermi="['dv_affairs:resident_record:shenhe']"></div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination style="font-size: 14px;" v-model:current-page="queryParams.pageNo" :hide-on-single-page="value"
      v-model:page-size="queryParams.pageSize" :page-sizes="pageSizes" layout="total,sizes,prev, pager, next,jumper"
      :total="total" @size-change="selectchange" @current-change="handleCurrentChange" />
  </div>
  <AddDialog v-show="addShow" :addShow="addShow" @getadd-show="getaddShow" :editData="editData"
    @getedit-data="geteditData" />
  <ExamineDialog v-show="examineShow" :examineShow="examineShow" @getexamine-show="getexamineShow" :editData="editData"
    @getedit-data="geteditData" />
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { dateFormatter2 } from '@/utils/formatTime'
import ResidentImportForm from './ResidentImportForm.vue'
import AddDialog from './components/addDialog.vue'
import ExamineDialog from './components/examineDialog.vue'
import download from '@/utils/download'
import globalApi from '@/api/spb/global'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as getgridApi from '@/api/countryside/gridmanagement/index'
const { push } = useRouter() // 路由
const selectList = ref([]) // 表格选中数据
const loading = ref(true) // 列表加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const value = ref(true)
const pageSizes = [10, 20, 50, 100]
const isHolderTypeObj = {
  0: '否',
  1: '是'
}
const sexTypeObj = {
  1: '男',
  2: '女'
}
const stateTypeObj = {
  1: '待审核',
  2: '审核通过',
  3: '审核驳回'
}
const optionstate = [
  {
    value: 1,
    label: '待审核'
  },
  {
    value: 2,
    label: '审核通过'
  },
  {
    value: 3,
    label: '审核驳回'
  }
]
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  residentName: '',
  houseNumber: '',
  residentType: '',
  auditStatus: '',
  residentLabel: []
})
const queryFormRef = ref() // 搜索的表单
const addShow = ref(false)
const examineShow = ref(false)
const contShow = ref(true)
const editData = ref({})
const getaddShow = (val) => {
  addShow.value = val
  contShow.value = !val
}
const getexamineShow = (val) => {
  examineShow.value = val
  contShow.value = !val
}
const geteditData = (val) => {
  handleCurrentChange(val)
}
/** 获取居民类型列表 */
const optiontype = ref([])
const gettypeTypeData = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_resident_type'
  }
  globalApi.getDictData(params).then((res) => {
    optiontype.value = res.list
  })
}
// 居民类型字段映射
const typetypeRelate = (item) => {
  let content = ''
  optiontype.value.forEach((t) => {
    if (t.value == item) {
      content = t.label
    }
  })
  return content
}
/** 获取民族类型列表 */
const optionnation = ref([])
const getnationTypeData = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_nation'
  }
  globalApi.getDictData(params).then((res) => {
    optionnation.value = res.list
  })
}
// 民族字段映射
const nationtypeRelate = (item) => {
  let content = ''
  optionnation.value.forEach((t) => {
    if (t.value == item) {
      content = t.label
    }
  })
  return content
}
/** 获取与户主关系类型列表 */
const optionrelation = ref([])
const getholdTypeData = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_relationship'
  }
  globalApi.getDictData(params).then((res) => {
    optionrelation.value = res.list
  })
}
// 与户主关系类型字段映射
const holdtypeRelate = (item) => {
  let content = ''
  optionrelation.value.forEach((t) => {
    if (t.value == item) {
      content = t.label
    }
  })
  return content
}
/** 获取户主列表 */
const optionholdId = ref([])
const getholdIdTypeData = () => {
  getgridApi.getHolder().then((res) => {
    optionholdId.value = res
  })
}
// 户主字段映射
const holdIdtypeRelate = (item) => {
  let content = ''
  optionholdId.value.forEach((t) => {
    if (t.id == item) {
      content = t.residentName
    }
  })
  return content
}

/** 条数变化 */
const selectchange = (e) => {
  queryParams.pageSize = e
  queryParams.pageNo = 1
  getList()
}
/** 页码变化 */
const handleCurrentChange = (e) => {
  queryParams.pageNo = e
  getList()
}

/** 状态背景色 */
const stateText = (item: any) => {
  const colors = ['rgba(247,165,67,0.4)', 'rgba(29,224,159,0.3)', 'rgba(234,44,16,0.3)']
  const colors2 = ['rgba(234,112,16,1)', 'rgba(57,144,115,1)', 'rgba(221,68,22,1)']
  let colorIndex = 0
  switch (item) {
    case optionstate[0].value:
      colorIndex = 0
      break
    case optionstate[1].value:
      colorIndex = 1
      break
    case optionstate[2].value:
      colorIndex = 2
      break
  }
  return {
    backgroundColor: colors[colorIndex],
    color: colors2[colorIndex]
  }
}

/*自动拆分省市区*/
const splitAddress = (address) => {
  var reg = /.+?(省|市|自治区|自治州|县|区)/g
  return address.match(reg)
}

/** 查询任务列表 */
const getList = async () => {
  getgridApi
    .getResidentPage(queryParams)
    .then((res) => {
      let data = reactive(res.list)
      data.forEach((item) => {
        if (item.isHolder === 1) {
          item.relationship = 11
        }
        item.residentLabel = item.residentLabel.split(',')
      })
      list.value = data
      total.value = res.total
      if (list.value.length === 0) {
        value.value = true
      } else {
        value.value = false
      }
      loading.value = false
    })
    .catch((error) => {
      loading.value = false
    })
}

/** 下载模版 */
const downloadbtn = () => {
  ElMessageBox.confirm('是否确认下载居民模版?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const data = await getgridApi.downloadResident()
      download.excel(data, '模板.xls')
      ElMessage({
        type: 'info',
        message: '正在请求资源请稍后',
        duration: 500
      })
      ElMessage.success('下载成功！')
    })
    .catch(() => {
      ElMessage.info('已取消下载')
    })
}

/** 批量导入 */
const importFormRef = ref()
const importbtn = () => {
  importFormRef.value.open()
}

/** 批量导出 */
const exportbtn = () => {
  ElMessageBox.confirm('是否确认批量导出居民?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const data = await getgridApi.exportResidentList(queryParams)
      download.excel(data, '居民.xls')
      ElMessage({
        type: 'info',
        message: '正在请求资源请稍后',
        duration: 500
      })
      ElMessage.success('下载成功！')
    })
    .catch(() => {
      ElMessage.info('已取消下载')
    })
}

/** 详情 */
const detailsbtn = (row: any) => {
  push({
    name: 'residentDetails',
    query: {
      id: row.id
    }
  })
}

/** 获取居民标签列表 */
let optionlabel2 = ref([])
const getresidentLabel = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_resident_label'
  }
  globalApi.getDictData(params).then((res) => {
    optionlabel2.value = []
    res.list.forEach((item) => {
      optionlabel2.value.push({
        label: item.label,
        value: item.value,
        selected: false
      })
    })
  })
}
// 居民标签字段映射
const labeltypeRelate = (item) => {
  let content = ''
  optionlabel2.value.forEach((t) => {
    if (t.value == item) {
      content = t.label
    }
  })
  return content
}
let labelList2 = reactive([])
/** 审核 */
const statebtn = async (row: any) => {
  getresidentLabel()
  optionstate.forEach((item) => {
    if (item.value == row.auditStatus) {
      row.auditStatus = item.label
    }
  })
  editData.value = row
  labelList2 = row.residentLabel
  optionlabel2.value.forEach((item) => {
    labelList2.forEach((item2) => {
      if (item2 === item.value) {
        item.selected = true
      }
    })
  })
  editData.value.optionlabel = optionlabel2.value
  editData.value.sex = JSON.stringify(row.sex)
  editData.value.isHolder = JSON.stringify(row.isHolder)
  editData.value.nation = nationtypeRelate(row.nation)
  editData.value.relationship = holdtypeRelate(row.relationship)
  editData.value.holderId = holdIdtypeRelate(row.holderId)
  editData.value.residentType = typetypeRelate(row.residentType)
  editData.value.pageNo = queryParams.pageNo
  examineShow.value = true
  contShow.value = false
}

/** 新增 */
const addbtn = () => {
  addShow.value = true
  contShow.value = false
  editData.value = {}
  editData.value.isHolder = '1'
  editData.value.sex = '1'
  editData.value.dialogtitle = '新增居民'
  editData.value.pageNo = 1
  editData.value.relationship = 11
}

/** 编辑 */
const editbtn = (row: any) => {
  getresidentLabel()
  addShow.value = true
  contShow.value = false
  editData.value = row
  labelList2 = row.residentLabel
  optionlabel2.value.forEach((item) => {
    labelList2.forEach((item2) => {
      if (item2 === item.value) {
        item.selected = true
      }
    })
  })
  editData.value.optionlabel = optionlabel2.value
  editData.value.sex = JSON.stringify(row.sex)
  editData.value.isHolder = JSON.stringify(row.isHolder)
  editData.value.dialogtitle = '编辑居民'
  editData.value.pageNo = queryParams.pageNo
  editData.value.place = splitAddress(row.address)
  if (Array.isArray(editData.value.place) && editData.value.place.length >= 2) {
    if (editData.value.place != '' && editData.value.place[0] === editData.value.place[1]) {
      editData.value.place[1] = '市辖区'
    }
  }
}

/** 批量删除 */
const handleSelectionChange = (e) => {
  selectList.value = e
}
const alldelbtn = () => {
  if (selectList.value.length == 0) {
    ElMessage({
      message: '至少选中一条数据！',
      type: 'warning'
    })
    return
  }
  ElMessageBox.confirm(`确认删除选中居民吗？删除当前选中居民会删除当前选中居民对应的网格员或网格长资格，请谨慎操作！`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      const idList = reactive([])
      selectList.value.forEach((item) => {
        idList.push(item.id)
      })
      getgridApi.deleteResidentList(idList).then((res) => {
        if (res === true) {
          ElMessage.success('删除成功！')
          getList()
        }
      })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}
/** 删除 */
const delbtn = (row: any) => {
  ElMessageBox.confirm(`确认删除居民【${row.residentName}】吗？删除当前居民会删除其对应的网格员或网格长资格，请谨慎操作！`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      getgridApi.deleteResident([row.id]).then((res) => {
        if (res === true) {
          ElMessage.success('删除成功！')
          getList()
        }
      })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

/** 查询按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 初始化 **/
onMounted(() => {
  getList()
  getholdTypeData()
  getholdIdTypeData()
  getnationTypeData()
  gettypeTypeData()
  getresidentLabel()
})
</script>

<style scoped>
.cont {
  background-color: rgba(255, 255, 255, 1);
  color: rgba(16, 16, 16, 1);
  font-size: 14px;
  text-align: center;
  min-height: 557px;
  position: relative;
}

.cont_top {
  text-align: left;
  margin: 4px 0;
}

::v-deep .el-table .cell {
  display: flex;
  justify-content: center;
}

::v-deep .el-input__wrapper.is-focus {
  box-shadow: 0 0 0 1px #cc352f;
}

::v-deep .el-select__wrapper.is-focused {
  box-shadow: 0 0 0 1px #cc352f;
}

.btn {
  width: 80px;
  height: 30px;
  line-height: 20px;
  border-radius: 5px;
  font-size: 14px;
  text-align: center;
}

.btnreset {
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(187, 187, 187, 1);
  color: rgba(142, 142, 142, 1);
}

.btnsearch {
  background-color: #cc352f;
  color: rgba(255, 255, 255, 1);
  border: 1px solid #cc352f;
}

.btn:hover {
  opacity: 0.8;
}

.btnhover:hover {
  opacity: 0.8;
}

.el-pagination {
  justify-content: center;
}

.namecont {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
}

.identity_style {
  min-width: 87px;
  height: 22px;
  line-height: 20px;
  text-align: center;
  border-radius: 5px;
  padding: 0 5px;
  margin: 0 2px;
  font-size: 12px;
  border: none;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  user-select: none;
  border: 1px solid rgba(16, 90, 215, 1);
  color: #437BC7;
  background: #F1F8FF;
}

.identity_style:hover {
  opacity: 0.8;
}

.state_style {
  width: 70px;
  height: 22px;
  line-height: 22px;
  text-align: center;
  border-radius: 25px;
  padding: 0 5px;
  font-size: 12px;
  border: none;
  cursor: pointer;
  user-select: none;
}

.state_style:hover {
  opacity: 0.8;
}

::v-deep .el-form-item__label {
  padding: 0 17px 0 0;
}

.upload-demo {
  height: 50px;
}

::v-deep.el-upload-list__item .el-upload-list__item-info {
  width: calc(100% - 0px);
}

::v-deep .el-upload-list .el-upload-list--text {
  position: absolute !important;
  top: 25px;
}

.label_style {
  display: flex;
  overflow-x: scroll;
  overflow-y: hidden;
  padding: 9px 0 6px 0;
}

::v-deep .el-table .cell.el-tooltip {
  display: block;
}

::v-deep .label_style::-webkit-scrollbar {
  height: 3px;
}

::v-deep .label_style:hover::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
}

::v-deep .label_style::-webkit-scrollbar-thumb {
  border-radius: 20px;
  background: transparent;
}

::v-deep .label_style::-webkit-scrollbar-track {
  display: none;
}
</style>